package com.example.work1.server.service.impl;

import com.example.work1.server.mapper.MajorMapper;
import com.example.work1.server.mapper.StudentMapper;
import com.example.work1.server.pojo.Major;
import com.example.work1.server.pojo.Student;
import com.example.work1.server.service.StudentService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.Random;

@Service
public class StudentServiceImpl implements StudentService {
    @Autowired
    private  StudentMapper studentMapper;
    @Autowired
    private MajorMapper majorMapper;

    @Override
    public void addStudent(Student student) {
        Date enrollmentDate = student.getEnrollmentDate();
        SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd");
        String enrollmentDateString = formatter.format(enrollmentDate);        // 随机生成专业
        Major major = getRandomMajor();
        // 生成ID= 专业编号 入学时间的年 依次增加的编号
        String id = generateId(String.valueOf(major.getId()), enrollmentDateString);

        student.setId(id);
        student.setMajorId(major.getId());

        studentMapper.insertStudent(student);
    }
    private String generateId(String major, String enrollmentDate) {
        int studentCounter=studentMapper.getStudentCount();
        String year = enrollmentDate.split("-")[0];
        return major + year + String.format("%03d", studentCounter++);
    }

    private Major getRandomMajor() {
        List<Major> majors = majorMapper.getAllMajors();
        Random random = new Random();
        return majors.get(random.nextInt(majors.size()));
    }
    @Override
    public Student getStudent(String id) {
        return studentMapper.getStudentById(id);
    }

    @Override
    public List<Student> getAllStudents() {
        return studentMapper.getAllStudents();
    }

    @Override
    public void updateStudent(Student student) {
        studentMapper.updateStudent(student);
    }

    @Override
    public void deleteStudent(String id) {
        studentMapper.deleteStudent(id);
    }
    @Override
    public int getStudentCount() {
        return studentMapper.getStudentCount();
    }

    @Override
    public List<Student> getTopScoringStudents() {
        return studentMapper.getTopScoringStudents();
    }
    @Override
    public List<Student> getLowestScoringStudents() {
        return studentMapper.getLowestScoringStudents();
    }

    @Override
    public List<Map<String, Object>> getStudentsGroupedByEnrollmentDate(){
        return studentMapper.getStudentsGroupedByEnrollmentDate();
    }
}
